package com.minimalist.lindi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Assert;
import com.minimalist.common.config.exception.BusinessException;
import com.minimalist.common.config.mybatis.bo.PageResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.minimalist.common.entity.lindi.enums.LindiPurchaseApplicationEnum;
import com.minimalist.common.entity.lindi.po.LindiPurchaseApplication;
import com.minimalist.common.entity.lindi.vo.purchaseapplication.LindiPurchaseApplicationQueryVO;
import com.minimalist.common.entity.lindi.vo.purchaseapplication.LindiPurchaseApplicationVO;
import com.minimalist.common.feign.client.basic.FileFeignClient;
import com.minimalist.common.response.R;
import com.minimalist.common.utils.UnqIdUtil;
import com.minimalist.lindi.manager.PurchaseApplicationManager;
import com.minimalist.lindi.mapper.LindiPurchaseApplicationMapper;
import com.minimalist.lindi.service.LindiPurchaseApplicationFileService;
import com.minimalist.lindi.service.LindiPurchaseApplicationProjectItemService;
import com.minimalist.lindi.service.LindiPurchaseApplicationService;
import com.minimalist.lindi.service.LindiPurchaseApplicationTownItemService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * 林地指标交易平台_指标购买申请表 服务层实现。
 *
 * @author 11987
 * @since 2025-07-01
 */
@Service
public class LindiPurchaseApplicationServiceImpl extends ServiceImpl<LindiPurchaseApplicationMapper, LindiPurchaseApplication> implements LindiPurchaseApplicationService{

    private static final Logger logger = LoggerFactory.getLogger(LindiPurchaseApplicationServiceImpl.class);

    @Autowired
    private LindiPurchaseApplicationMapper mapper;

    @Autowired
    private PurchaseApplicationManager purchaseApplicationManager;

    @Autowired
    private LindiPurchaseApplicationFileService purchaseApplicationFileService;

    @Autowired
    private LindiPurchaseApplicationProjectItemService purchaseApplicationProjectItemService;

    @Autowired
    private LindiPurchaseApplicationTownItemService purchaseApplicationTownItemService;

    @Autowired
    private FileFeignClient fileFeignClient;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addPurchaseApplication(LindiPurchaseApplicationVO purchaseApplicationVO){
        LindiPurchaseApplication record = BeanUtil.copyProperties(purchaseApplicationVO, LindiPurchaseApplication.class);
        record.setPurchaseApplicationId(UnqIdUtil.uniqueId());
        record.setPurchaseApplicationStatus(LindiPurchaseApplicationEnum.StatusEnum
                .PENDING_APPROVAL.getCode().toString());
        int insert = mapper.insert(record, true);
        Assert.isTrue(insert == 1, () -> new BusinessException("添加指标购买申请失败"));

        // 保存关联数据
        purchaseApplicationVO.setPurchaseApplicationId(record.getPurchaseApplicationId());
        purchaseApplicationManager.saveRelatedData(purchaseApplicationVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePurchaseApplicationByPurchaseApplicationId(Long purchaseApplicationId){
        LindiPurchaseApplication record = mapper
                .selectPurchaseApplicationByPurchaseApplicationId(purchaseApplicationId);
        Assert.notNull(record, () -> new BusinessException("指标购买申请不存在"));

        // 删除关联数据
        purchaseApplicationManager.deleteRelatedData(purchaseApplicationId);

        int delete = mapper.deletePurchaseApplicationByPurchaseApplicationId(purchaseApplicationId);
        Assert.isTrue(delete == 1, () -> new BusinessException("删除指标购买申请失败"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePurchaseApplicationByPurchaseApplicationId(LindiPurchaseApplicationVO purchaseApplicationVO){
        LindiPurchaseApplication record = mapper
                .selectPurchaseApplicationByPurchaseApplicationId(purchaseApplicationVO.getPurchaseApplicationId());
        Assert.notNull(record, () -> new BusinessException("指标购买申请不存在"));

        BeanUtil.copyProperties(purchaseApplicationVO, record, CopyOptions.create().ignoreNullValue());

        int update = mapper.update(record);
        Assert.isTrue(update == 1, () -> new BusinessException("修改指标购买申请失败"));

        // 更新关联数据
        purchaseApplicationVO.setPurchaseApplicationId(purchaseApplicationVO.getPurchaseApplicationId());
        purchaseApplicationManager.updateRelatedData(purchaseApplicationVO);
    }

    @Override
    public PageResp<LindiPurchaseApplicationVO> getPagePurchaseApplicationList(LindiPurchaseApplicationQueryVO queryVO){
        // 分页查询
        Page<LindiPurchaseApplication> purchaseApplicationPage = mapper
                .selectPagePurchaseApplicationList(queryVO);
        // 数据转换
        List<LindiPurchaseApplicationVO> purchaseApplicationVOList =
                BeanUtil.copyToList(purchaseApplicationPage.getRecords()
                        , LindiPurchaseApplicationVO.class);
        return new PageResp<>(purchaseApplicationVOList
                , purchaseApplicationPage.getTotalRow());
    }

    @Override
    public LindiPurchaseApplicationVO getPurchaseApplicationByPurchaseApplicationId(Long purchaseApplicationId){
        LindiPurchaseApplication record = mapper
                .selectPurchaseApplicationByPurchaseApplicationId(purchaseApplicationId);
        Assert.notNull(record, () -> new BusinessException("指标购买申请不存在"));

        // 构建完整的VO对象（包含关联数据）
        return purchaseApplicationManager.buildCompleteVO(record);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePurchaseApplicationFileByFileId(Long fileId){
        // 删除文件系统中的文件
        try {
            R<Void> result = fileFeignClient.deleteFile(fileId);
            if (result.getCode() != 200) {
                logger.warn("删除指标购买申请文件失败，文件ID: {}, 错误码: {}", fileId, result.getCode());
            }
        } catch (Exception e) {
            logger.warn("删除指标购买申请文件时发生异常，文件ID: {}, 异常信息: {}", fileId, e.getMessage(), e);
        }

        // 删除文件关联记录
        purchaseApplicationFileService.deleteFileByFileId(fileId);
    }
}